#include "networkzingmeconnection.h"
#include "network/networkconnectionrequest.h"
#include "networkzingmewebsocket.h"

using namespace Network::Zingme;
/**
 * @brief Connection::Connection
 * @param parent
 */

Connection::Connection(QObject *parent):
    Network::Connection(parent),
    m_websocket(NULL)
{
}

Connection::~Connection()
{
    if (m_websocket == NULL)
        return;
    m_websocket->disconnect();
    delete m_websocket;
    m_websocket = NULL;
    emit disconnected();
}

bool Connection::connect(const QString server, unsigned int port, const QVariant &params)
{
    if (m_websocket != NULL || params.type() != QVariant::Map)
        return false;

    m_websocket = new Websocket(this);
    QObject::connect(m_websocket, &Websocket::connected, this, &Connection::onConnected);
    QObject::connect(m_websocket, &Websocket::received, this, &Connection::onReceived);
    QObject::connect(m_websocket, &Websocket::disconnected, this, &Connection::onDisconnected);

    if (!m_websocket->connect(server, port, params)) {
        delete m_websocket;
        m_websocket = NULL;
        return false;
    }
    return true;
}

bool Connection::reconnect()
{
    return true;
}

bool Connection::isConnected() const
{
    if (m_websocket == NULL)
        return false;
    return true;
//    return m_websocket->isConnected();
}

bool Connection::post(ConnectionRequest *request)
{
    if (m_websocket == NULL)
        return false;
    return m_websocket->send(request);
}

bool Connection::disconnect()
{
    m_websocket->disconnect();
    emit disconnected();
    return true;
}

void Connection::onConnected()
{
    if (m_websocket == NULL)
        return;
    emit connected();
}

void Connection::onReceived(QByteArray message)
{
    if (m_websocket == NULL)
        return;
    emit received(message);
}

void Connection::onDisconnected()
{
    if (m_websocket == NULL)
        return;
    delete m_websocket;
    m_websocket = NULL;
    emit disconnected();
}
